import pymysql
from dbutils.pooled_db import PooledDB
from config.settings import MYSQL_CONFIG
from utils.log_handler import logger


class DBHelper(object):
    def __init__(self):
        # MYSQL_CONFIG: mysql相关的配置文件
        self.pool = PooledDB(**MYSQL_CONFIG)
        self.conn = None
        self.cursor = None

    def get_conn_cursor(self):
        try:
            self.conn = self.pool.connection()
            self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
            logger.info("数据库连接成功")
            return self.conn, self.cursor
        except Exception as e:
            logger.error(f"数据库连接出错：{e}")

    def close_conn_cursor(self):
        self.cursor.close()
        self.conn.close()
        logger.info("关闭数据库")

    def exec(self, sql, **kwargs):
        # conn, cursor = self.get_conn_cursor()
        logger.info(f"执行sql：{sql}")
        try:
            result = self.cursor.execute(sql, kwargs)
            logger.info(f"执行结果：{'成功' if not result else '失败'}")
            self.conn.commit()
        except Exception as e:
            logger.error(f"执行sql失败：{e}")
        # self.close_conn_cursor(conn, cursor)

    def fetch_one(self, sql, **kwargs):
        # conn, cursor = self.get_conn_cursor()
        logger.info(f"查询sql：{sql}")
        try:
            self.cursor.execute(sql, kwargs)
            result = self.cursor.fetchone()
            logger.info(f"查询结果：{result}")
            # self.close_conn_cursor(conn, cursor)
            return result
        except Exception as e:
            logger.error(f"查询sql失败：{e}")

    def fetch_all(self, sql, **kwargs):
        # conn, cursor = self.get_conn_cursor()
        logger.info(f"查询sql：{sql}")
        try:
            self.cursor.execute(sql, kwargs)
            result = self.cursor.fetchall()
            logger.info(f"查询结果：{result}")
            # self.close_conn_cursor(conn, cursor)
            return result
        except Exception as e:
            logger.error(f"查询sql失败：{e}")


db = DBHelper()
